import {storeBindingsBehavior} from "mobx-miniprogram-bindings";
import cart from "../../store/cart";
import {getProDetail,getShopDetail} from '@src/api/catering'
import router from '@src/router'


Component({
  options: {
    addGlobalClass: true
  },
  behaviors: [storeBindingsBehavior],
  storeBindings: [{
    store: cart,
    actions: ['addCart'],
  }],
  data: {
    visible: true,
    goods: null,
    spec: "",
    specPrice: 0,
    resolve: null,
    reject: null,
    selectAttrList: [],
    tips: "",
    isFold:false,
    goodImg:[],
    giftStr:'',
    proNum:1,
    shopId:'',
    login:false,
    shopInfo:{},
    queryParams:{}
  },
  observers: {
    'spec,selectAttrList': function (spec, selectAttrList) {
      let tips = [];
      if (spec) {
        tips.push(spec)
      }
      tips.push(...selectAttrList);
      this.setData({tips: tips.join(","),proNum:1})
    }
  },
  methods: {
    onLogin() {
      this.updateStoreBindings();
      this.setData({ login: true })
      this.getProDetail()

    },
    onAnon() {
      this.updateStoreBindings();
      this.setData({ login: false});
    },
    onShareAppMessage(e) {
      let {shareText,imageUrl} = this.data.goods
      let {queryParams:{shopId,itemId,classifyId}} = this.data
      imageUrl?imageUrl:img='https://hyyxboss.oss-cn-shenzhen.aliyuncs.com/business/1/shop_default_logo.png'
      return {
        title: shareText,
        imageUrl: getApp().toFullUrl(imageUrl),
        path: `pages/codeModul/pages/proDetail/main?shopId=${shopId}&itemId=${itemId}&classifyId=${classifyId}`,
        success: (res) => {}
      }
    },
    onLoad(options){
      if(options&&options.shopId&&options.shopId){
        let {shopId,itemId,classifyId} = options
        this.setData({queryParams:{shopId,itemId,classifyId}})
      }
      getApp().globalData.dinnerShopid = options.shopId
      // this.getProDetail()
      wx.showShareMenu({
        withShareTicket: true,
        menus: ['shareAppMessage', 'shareTimeline']
      })
    },
    getProDetail(){
      let {queryParams,queryParams:{shopId}} = this.data
      getShopDetail({shopId}).then(res=>{
        if(res.code == 0){
          this.setData({shopInfo:res.data})
          if(getApp().globalData.dinnerType == 0){
           if( res.data.orderTypes.indexOf(1) !== -1){
             getApp().globalData.dinnerType = 1
           }else if(res.data.orderTypes.indexOf(2) !== -1){
            getApp().globalData.dinnerType = 2
           }
          }
        }
      })
      getProDetail(queryParams).then(res=>{
        if(res.code == 0){
          this.reset(res.data)
        }
      })
    },
    reset(goods) {
      this.setData({shopId:getApp().globalData.dinnerShopid})
      let {ruleList} = goods
      let giftStr = []
      let spec = "", specPrice, selectAttrList = [];
      if (goods.specList && goods.specList.length > 0) {
        spec = goods.specList[0].name
        specPrice = goods.specList[0].price
      }
      // 商品轮播图
      if(goods.itemImages){
        let imgList = goods.itemImages.split(',')
        let fileBaseUrl = getApp().globalData.extConfig.fileBaseUrl;
        imgList.forEach((el,index) => {
          imgList[index] = fileBaseUrl+el
        });
        this.setData({goodImg:imgList})
      }else{
        this.setData({goodImg:[goods.imageUrl]})
      }
      // 展示赠品信息
      if(ruleList&&ruleList.length>0){
        ruleList.forEach(e=>{
          let childRule = JSON.parse(e.rules)
          if(childRule&&childRule.length>0){
            childRule.forEach(ele=>{
              giftStr.push(`购买${ele.itemNum}份商品赠送${e.sellgiftName}x${ele.giftNum}`)
            })
          } 
        })
      }
      // 默认设置第一个属性
      if (goods.attrList && goods.attrList.length > 0) {
        for (let item of goods.attrList) {
          selectAttrList.push(item.values[0])
        }
      }
      this.setData({goods, spec, specPrice, selectAttrList,giftStr})
    },
    handleSelectSpec(e) {
      let item = e.currentTarget.dataset.item;
      if (item.name === this.data.spec) {
        return;
      }
      this.setData({
        spec: item.name,
        specPrice: item.price,
      })
    },
    handleSelectAttr(e) {
      let {index, value} = e.currentTarget.dataset;
      let selectAttrList = this.data.selectAttrList
      selectAttrList[index] = value;
      this.setData({selectAttrList})
    },
    handleConfirm() {
      let item = {};
      let {goods:{name,price,specList,id,imageUrl,ruleList},specPrice,selectAttrList,spec,proNum,tips} = this.data
      item = {
        name,
        id,
        count:proNum,
        imageUrl,
        spec,
        ruleList,
        price:spec?specPrice:price,
        attrList:selectAttrList,
        remark:tips
      }
      
      this.addCart(item);
      this.setData({proNum:1})
    },

    handleOp(e){
      let {op} =e.currentTarget.dataset
      let {proNum} = this.data
      if(op == 'reduce'){
        if(proNum<=1){
          wx.showToast({
            title: '数量不能小于1',
            icon: 'error',
            duration: 2000
          })
          return
        }
        this.setData({proNum:proNum-1})
      }else{
        if(proNum>99){
          wx.showToast({
            title: '数量不能大于99',
            icon: 'error',
            duration: 2000
          })
          return
        }
        this.setData({proNum:proNum+1})
      }
    },
    handleToPay() {
      let item = {};
      let {goods:{name,price,specList,id,imageUrl,ruleList},specPrice,selectAttrList,spec,proNum,tips} = this.data
      item = {
          name,
          id,
          count:proNum,
          imageUrl,
          spec,
          ruleList,
          price:spec?specPrice:price,
          attrList:selectAttrList,
          remark:tips
      }
      // if(item.ruleList&&item.ruleList.length>0){
      //   item.ruleList.forEach(e=>{
      //     e.rules = JSON.stringify(e.rules)
      //   })
      // }
      let allPrice  = (item.price*proNum).toFixed(2)
      this.handOnePay({carList:[item],totalFree:allPrice})
      this.setData({proNum:1})
    },
    handOnePay(detail){
      let {carList,totalFree} = detail
      router.push({
        name: 'codeorder/order',
        params: {
          shopId: this.data.queryParams.shopId,
        },
        success: (res) => {
          res.eventChannel.emit('order', {
            shopId: this.data.queryParams.shopId,
            shopInfo: this.data.shopInfo,
            cartList: detail.carList,
            totalFee: detail.totalFree,
          })
        },
      })},
    changeDese(){
      let {data:{isFold}} = this
      this.setData({isFold:!isFold})
    },
    sharePro(){
     this.selectComponent("#sharePro").handleToSavePoster();
     this.handleClose()
    }
  }
});
